# -*- coding: utf-8 -*-
import argparse

from contract_market.core.core import EventCenter  # NOQA
from contract_market.initialize.log import InitLogConfig  # NOQA
from contract_market.server.engine import EventEngine, QuantListener  # NOQA
from contract_market.strategy.image.manager import ImageMarketEngine  # NOQA
from contract_market.initialize.config import InitConfig  # NOQA
from contract_market.common.common import EventSystemEngine  # NOQA


class Argv:
    symbol_name = ""
    process_name = ""


class ArgvAction(argparse.Action):
    def __init__(self, option_strings, dest, nargs=None, **kwargs):
        if nargs is not None:
            raise ValueError("nargs not allowed")
        super(ArgvAction, self).__init__(option_strings, dest, **kwargs)

    def __call__(self, parser, namespace, values, option_string=None):
        setattr(Argv, self.dest, values)
        setattr(namespace, self.dest, values)


class MainProcess:

    def __init__(self, back: object = None) -> None:
        """ """
        parser = argparse.ArgumentParser(description='Process some params.')
        parser.add_argument('-s', dest='symbol_name', action=ArgvAction,
                            help='Please enter the name of the enabled policy market', required=True)
        parser.add_argument('-p', dest='process_name', action=ArgvAction,
                            help='Enter a process name, making sure that the process name is the same as the name of the process management tool and that there is a joint constraint between the market and process names',
                            required=True)
        parser.parse_args()
        self._doBack = back
        InitLogConfig()

    def init_engine(self):
        """ """
        event = EventCenter()
        engine = EventEngine(event)
        engine.add_extra_class(self._doBack.name, self._doBack)
        engine.add_engine(QuantListener)
        engine.add_engine(EventSystemEngine)
        return event, engine

    def start(self):
        """ """
        event, engine = self.init_engine()
        # load configure
        cfg = InitConfig("image", "pair.yaml", argv=Argv)
        print("[cfg]", cfg.resolve(), Argv.process_name)

        # add strategy
        engine.add_engine(ImageMarketEngine, configure=cfg, back=self._doBack)

        # add callback
        cf = engine._engines.get('ImageMarketEngine').orderbook.stop_all
        self._doBack.set_callback(cf)

        # start 
        engine.start()
        return engine
